<template>
    <div class="wrapper" v-if="isBindWeChat == 1 || isBindWeChat == 2">
        <div class="left">
            <div class="left-pic" />
        </div>
        <div class="right">
            <el-form
                ref="loginForm"
                :model="loginForm"
                :rules="loginRules"
                class="login-form"
                auto-complete="on"
                label-position="left"
            >
                <div class="title">{{name}}</div>
                <div v-if="loginType == 1">
                    <el-form-item prop="username">
                        <el-input
                            ref="name"
                            v-model="loginForm.username"
                            autofocus="autofocus"
                            name="username"
                            type="text"
                            auto-complete="on"
                            placeholder="请输入用户名"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input
                            type="password"
                            v-model="loginForm.password"
                            name="password"
                            auto-complete="on"
                            placeholder="请输入密码"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            :loading="loading"
                            @click.native.prevent="handleLogin"
                            class="submit-btn"
                        >
                            登录
                        </el-button>
                    </el-form-item>
                </div>
                <div
                    class="wx-login"
                    v-else
                >
                    <div
                        class="login-eqcode"
                        id="wx_reg"
                    >
                        <iframe
                            :src="iframeUrl"
                            frameborder="0"
                        ></iframe>
                    </div>
                    <!-- <div class="login-eqcode-title">请使用手机企业微信扫码登录</div> -->
                </div>
                <div
                    v-if="isBindWeChat == 1"
                    class="change-login-type"
                    @click="changeLoginType"
                >{{loginType == 1 ? "扫码登录" : "账号密码登录"}}</div>
            </el-form>
            <div class="copyright">金谷科技CRM系统<br>
                <a
                    target="_blank"
                    href="javascript:;"
                >©2019 金谷科技CRM</a>
            </div>
        </div>

        <img
            class="logo"
            :src="logo"
        />
        <!-- 绑定微信 -->
        <el-dialog
            title="绑定企业微信"
            :center="true"
            :visible.sync="dialogFormBind"
            width="350px"
            top="20vh"
            :close-on-click-modal="false"
        >
            <el-form
                ref="bindLoginForm"
                :model="bindLoginForm"
                :rules="bindLoginRules"
                class="login-form"
                auto-complete="on"
                label-position="left"
            >
                <div>
                    <el-form-item prop="username">
                        <el-input
                            ref="name"
                            v-model="bindLoginForm.username"
                            autofocus="autofocus"
                            name="username"
                            type="text"
                            auto-complete="on"
                            placeholder="请输入用户名"
                            @keyup.enter.native="handleBindLogin"
                        />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input
                            type="password"
                            v-model="bindLoginForm.password"
                            name="password"
                            auto-complete="on"
                            placeholder="请输入密码"
                            @keyup.enter.native="handleBindLogin"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            :loading="bindLoading"
                            size="small"
                            @click.native.prevent="handleBindLogin"
                            class="bind-btn"
                            type="pr"
                        >
                            绑定
                        </el-button>
                    </el-form-item>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import Lockr from "lockr";
import { Loading } from "element-ui";
import { getWechatConfigAPI, wxqyLoginAPI } from "@/api/login";

export default {
    name: "Login",
    data() {
        const validateUsername = (rule, value, callback) => {
            if (value.length == 0) {
                callback(new Error("请输入账号"));
            } else {
                callback();
            }
        };
        const validatePass = (rule, value, callback) => {
            if (value.length < 5) {
                callback(new Error("密码不能小于5位"));
            } else {
                callback();
            }
        };
        return {
            isBindWeChat: 1,
            // 绑定
            dialogFormBind: false,
            bindLoginForm: {
                username: "",
                password: ""
            },
            bindLoginRules: {
                username: [
                    {
                        required: true,
                        trigger: "blur",
                        validator: validateUsername
                    }
                ],
                password: [
                    { required: true, trigger: "blur", validator: validatePass }
                ]
            },
            bindLoading: false,
            // 登录
            loginForm: {
                username: "",
                password: ""
            },
            loginRules: {
                username: [
                    {
                        required: true,
                        trigger: "blur",
                        validator: validateUsername
                    }
                ],
                password: [
                    { required: true, trigger: "blur", validator: validatePass }
                ]
            },
            loading: false,
            redirect: undefined,
            remember: false,
            loginType: 1, // 1：账号密码登录； 2：企业微信登录
            qWxQRcode: "",
            iframeUrl: "",
            wechat_id: "",
        };
    },
    components: {},
    watch: {
        $route: {
            handler: function(route) {
                this.redirect = route.query && route.query.redirect;
            },
            immediate: true
        }
    },
    computed: {
        ...mapGetters(["logo", "name"])
    },
    mounted() {
        if (this.$route.query.code) {
            this.isBindWeChat = 3
            this.wxqyLogin()
        } else {
            this.getLoginConfig();
        }
    },
    methods: {
        // 绑定
        handleBindLogin () {
            if (!this.wechat_id) {
                this.$confirm('请用企业微信扫码后再绑定账号!', '提示', {
                    showCancelButton: false,
                    confirmButtonText: '确定',
                    showClose: false,
                    closeOnClickModal: false,
                    type: 'warning'
                }).then(() => {
                    this.dialogFormBind = false
                    this.loginType = 2
                }).catch(() => {
                    this.dialogFormBind = false
                    this.loginType = 2
                });
                return null;
            }
            this.$refs.bindLoginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    let params = {
                        username: this.bindLoginForm.username.trim(),
                        password: this.bindLoginForm.password,
                        wechat_id: this.wechat_id,
                    }
                    this.$store
                        .dispatch("Login", params)
                        .then(res => {
                            this.loading = false;
                            this.$router.push({ path: this.redirect || "/" });
                        })
                        .catch(() => {
                            this.loading = false;
                        });
                } else {
                    return false;
                }
            });
        },
        // 登录
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    let params = {
                        username: this.loginForm.username.trim(),
                        password: this.loginForm.password
                    }
                    this.$store
                        .dispatch("Login", params)
                        .then(res => {
                            this.loading = false;
                            this.$router.push({ path: this.redirect || "/" });
                        })
                        .catch(() => {
                            this.loading = false;
                        });
                } else {
                    return false;
                }
            });
        },
        // 获取登录配置
        getLoginConfig() {
            let params = {};
            getWechatConfigAPI(params)
                .then(res => {
                    if (res.data) {
                        this.qWxQRcode = res.data.redirect_uri;
                        let c = res.data;
                        var redirect_uri = "http://jingu.3todo.com";
                        this.iframeUrl = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=${c.appid}&agentid=${c.agentid}&redirect_uri=${redirect_uri}&state=${c.state}&login_type=jssdk`;
                    }
                })
                .catch(() => {});
        },
        // code 登录
        wxqyLogin() {
            let params = {
                code: this.$route.query.code
            };
            this.loading = true;
            this.$store
                .dispatch("WxLogin", params)
                .then(res => {
                    if (res.code == 200) {
                        this.$router.push({ path: this.redirect || "/" });
                    } else if (res.code == 405) {
                        this.$message({
                            type: "warning",
                            message: res.msg
                        });
                        this.wechat_id = res.data.wechat_id
                        this.isBindWeChat = 2
                        this.dialogFormBind = true
                    } else {
                        this.$message({
                            type: "warning",
                            message: res.msg
                        });
                        this.isBindWeChat = 1
                    }
                    this.loading = false;
                })
                .catch((res) => {
                    if (res.code == 200) {
                        this.$router.push({ path: this.redirect || "/" });
                    } else if (res.code == 405) {
                        this.$message({
                            type: "warning",
                            message: res.error
                        });
                        this.wechat_id = res.data.wechat_id
                        this.isBindWeChat = 2
                        this.dialogFormBind = true
                    } else {
                        this.$message({
                            type: "warning",
                            message: res.error
                        });
                        this.isBindWeChat = 1
                    }
                    this.loading = false;
                });
        },

        // 切换登录方式
        changeLoginType() {
            if (this.loginType == 1) {
                this.loginType = 2;
            } else {
                this.loginType = 1;
            }
        }
    }
};
</script>

<style lang="scss" scoped>
$dark_gray: #ccc;
$light_gray: #333;
$login_theme: #00aaee;

/deep/ input {
    border: 0 none;
    background-color: white;
    -webkit-appearance: none;
    &:-webkit-autofill {
        background-image: none;
        -webkit-box-shadow: 0 0 0 1000px white inset !important;
        -webkit-text-fill-color: $light_gray !important;
    }
}
/deep/ .el-input__inner {
    height: 40px;
    padding: 0 12px;
    background-color: white;
    border: 0 none;
    border-bottom: 1px solid #e6e6e6 !important;
}
/deep/ .el-form-item__error {
    left: 12px;
}
.wrapper {
    position: relative;
    width: 100%;
    min-width: 1300px;
    display: flex;
    .left {
        width: 68%;
        .left-pic {
            width: 100%;
            height: 100%;
            background: url("../../assets/img/login/login.png") no-repeat center;
            background-size: cover;
        }
    }
    .right {
        position: relative;
        width: 32%;
        background-color: #fff;
        display: flex;
        align-items: center;
        flex-direction: column;
        padding-top: 6%;
        .el-form {
            width: 70%;
            .title {
                font-size: 26px;
                color: $light_gray;
                margin: 0 auto 50px;
                text-align: center;
            }
            .submit-btn {
                width: 100%;
                line-height: 2;
                font-size: 16px;
                color: white;
                border-radius: 3px;
                background-color: $login_theme;
                display: block;
            }
            .el-button {
                border: 0 none;
            }
            .action-control {
                color: #999;
                /deep/ .el-checkbox {
                    .el-checkbox__label {
                        color: #999;
                    }
                    .el-checkbox__input.is-checked .el-checkbox__inner {
                        background-color: $login_theme;
                        border-color: $login_theme;
                    }
                }

                .forget {
                    cursor: pointer;
                    float: right;
                }
            }
        }

        .register {
            width: 70%;
            padding-top: 30px;
            color: $light_gray;
            border-top: 1px solid #e6e6e6;
            text-align: center;
            margin-top: 28px;
            .register-btn {
                color: $login_theme;
                cursor: pointer;
            }
        }

        .copyright {
            width: 92%;
            position: absolute;
            bottom: 2%;
            color: #d0d0d0;
            font-size: 12px;
            text-align: center;
            line-height: 1.5;
        }
    }

    .logo {
        position: absolute;
        left: 60px;
        top: 50px;
        width: 180px;
        height: 48px;
        z-index: 200;
    }
}
// 扫码登录
.wx-login {
    .login-eqcode {
        width: 300px;
        height: 400px;
        margin: 0 auto;
        iframe {
            height: 100%;
            width: 100%;
        }
    }
    .login-eqcode-title {
        font-size: 14px;
        color: #333;
        text-align: center;
        line-height: 40px;
    }
}
.change-login-type {
    font-size: 14px;
    color: #00aaee;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
}
.bind-btn{
    width: 100%;
    line-height: 1.6;
    font-size: 16px;
    color: #fff;
    border-radius: 3px;
    border-color: #0ae;
    background-color: #0ae;
    display: block;
    margin-top: 20px;
}
</style>
